<?php
/**
 * Created by PhpStorm.
 * User: huihui
 * Date: 2019/8/19
 * Time: 10:24 PM
 */

namespace app\api\library;

/**
 * 宝塔API接口示例Demo
 * 仅供参考，请根据实际项目需求开发，并做好安全处理
 * date 2018/12/12
 * author 阿良
 */
class Bt {
    private $BT_KEY = "JTTpDEWrhLElejNMRRwJLbYJ5H3uroU8";  //接口密钥
    private $BT_PANEL = "http://127.0.0.1:55555";	   //面板地址

    //如果希望多台面板，可以在实例化对象时，将面板地址与密钥传入
    public function __construct($bt_panel = null,$bt_key = null){
        if($bt_panel) $this->BT_PANEL = $bt_panel;
        if($bt_key) $this->BT_KEY = $bt_key;
    }

    /**
     * 添加域名
     * @param $data
     * @return mixed
     */
    public function addDomain($data)
    {
        $url = $this->BT_PANEL.'/site?action=AddDomain';
        $p_data = $this->GetKeyData();
        $p_data['domain'] = $data['domain'];
        $p_data['webname'] = $data['webname'];
        $p_data['id'] = $data['id'];
        //请求面板接口
        $result = $this->HttpPostCookie($url,$p_data);
        //解析JSON数据
        $data = json_decode($result,true);
        return $data;
    }


    public function DelDomain($data)
    {
        $url = $this->BT_PANEL.'/site?action=DelDomain';
        $p_data = $this->GetKeyData();
        $p_data['domain'] = $data['domain'];
        $p_data['webname'] = $data['webname'];
        $p_data['id'] = $data['id'];
        $p_data['port'] = $data['port'];
        //请求面板接口
        $result = $this->HttpPostCookie($url,$p_data);
        //解析JSON数据
        $data = json_decode($result,true);
        return $data;
    }


    /**
     * 构造带有签名的关联数组
     */
    private function GetKeyData(){
        $now_time = time();
        $p_data = array(
            'request_token'	=>	md5($now_time.''.md5($this->BT_KEY)),
            'request_time'	=>	$now_time
        );
        return $p_data;
    }


    /**
     * 发起POST请求
     * @param String $url 目标网填，带http://
     * @param Array|String $data 欲提交的数据
     * @return string
     */
    private function HttpPostCookie($url, $data,$timeout = 60)
    {
        //定义cookie保存位置
        $cookie_file='/tmp/'.md5($this->BT_PANEL).'.cookie';
        if(!file_exists($cookie_file)){
            $fp = fopen($cookie_file,'w+');
            fclose($fp);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $output = curl_exec($ch);
//        $error = curl_error($ch);
        curl_close($ch);
        return $output;
    }
}

